package com.lzh.gulimall.seckill.interceptor;

import com.lzh.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.lzh.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @ClassName LoginUserInterceptor
 * @Description TODO
 * @Author liuzhihui
 * @Date 2020/9/4 0:16
 * @Version 1.0
 **/
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberResponseVo> loginUser=new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 如果是微服务之间的调用无需登录
         */
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", requestURI);
        if (match ){
            //从session中获取用户信息
            MemberResponseVo memberResponseVo = (MemberResponseVo) request.getSession().getAttribute(LOGIN_USER);

            //登录了
            if (memberResponseVo!=null){
                //将用户信息放入到ThreadLocal中，方便使用
                loginUser.set(memberResponseVo);
                return true;
            }
            //没登录
            else {
                request.getSession().setAttribute("msg","请先进行登录");
                //跳转到登录页面
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }
     return true;
    }
}
